package com.iven.xie.es.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.iven.xie.es.common.EsUtil;
import com.iven.xie.es.entity.EsEntity;
import com.iven.xie.es.entity.doc.ProductDocument;
import com.iven.xie.es.service.EsSearchService;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * elasticsearch 搜索引擎 service实现
 *
 * @author iven.xie
 * @version 1.0
 * @date 2020/02/28 18:15
 */
@Service
public class EsSearchServiceImpl extends BaseSearchServiceImpl<ProductDocument> implements EsSearchService {
    private Logger log = LoggerFactory.getLogger(getClass());

    @Override
    public void save(ProductDocument productDocuments) {
        EsEntity<ProductDocument> entity = new EsEntity<ProductDocument>();
        entity.setId(productDocuments.getId());
        entity.setData(productDocuments);
        this.insertOrUpdateOne(EsUtil.PRODUCT_DOCUMENT_INDEX_NAME, entity);
        log.info("【保存数据】：{}", JSON.toJSONString(entity.getData()));
    }

    @Override
    public void saveBatch(List<ProductDocument> productDocuments) {
        List<EsEntity> list = Lists.newArrayList();
        productDocuments.forEach(item -> list.add(new EsEntity<>(item.getId(), item)));
        this.insertBatch(EsUtil.PRODUCT_DOCUMENT_INDEX_NAME, list);
    }

    @Override
    public void delete(String id) {
        this.deleteByQuery(EsUtil.PRODUCT_DOCUMENT_INDEX_NAME, new TermQueryBuilder("id", id));
    }

    @Override
    public void deleteAll() {
        this.deleteIndex(EsUtil.PRODUCT_DOCUMENT_INDEX_NAME);
        this.initIndex(EsUtil.PRODUCT_DOCUMENT_INDEX_NAME);
    }

    @Override
    public ProductDocument getById(String id) {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(new TermQueryBuilder("id", id));
        List<ProductDocument> res = this.search(EsUtil.PRODUCT_DOCUMENT_INDEX_NAME, builder, ProductDocument.class);
        if (res.size() > 0) {
            return res.get(0);
        } else {
            return null;
        }
    }

    @Override
    public List<ProductDocument> getAll() {
        return this.search(EsUtil.PRODUCT_DOCUMENT_INDEX_NAME, new SearchSourceBuilder(), ProductDocument.class);
    }

}
